package com.usermanage.controller;

import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.*;
import com.usermanage.beanParam.*;
import com.usermanage.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * 用户信息操作
 */
@Slf4j
@Api(description = "用户信息操作接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private GroupService groupService;
    @Resource
    private UserService userService;

    @Resource
    private GroupMemberService groupMemberService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private GroupPermissionService groupPermissionService;
    @Resource
    private UserCenterService userCenterService;


    /**
     * 用户首页列表
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list.page", method = RequestMethod.GET)
    public ModelAndView list() throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/user/list");
        return mv;
    }

    /**
     * 用户首页列表数据
     *
     * @param key
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list.json", method = RequestMethod.POST)
    public JsonData roleListJson(String key, String page, String size) throws Exception {
        if (StringUtils.isBlank(page)) {
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(size)) {
            size = StaticUtil.sizeCount;
        }

        //得到用户的列表
        List<UserBean> list = userService.getAllUserList(key, page, size);
//        //根据用户组的uuid得到用户的角色列表记录数
        int count = userService.getAllUserListCount(key);
//        //从用户信息中获取权限列表，此处拼接列表的权限button按钮
        List<PermissionBean> permissionBeanList = SpringSecurityUtils.getCurrentUser().getList();
        List<Map> operaButton = new ArrayList<>();
        for (PermissionBean bean : permissionBeanList) {
            if (bean.getPermission_url().equals("/user/cancel.json")) {
                Map map = new HashMap();
                map.put("name", bean.getPermission_name());
                map.put("fn", "del");
                operaButton.add(map);
            }
            if (bean.getPermission_url().equals("/user/update.page")) {
                Map map = new HashMap();
                map.put("name", bean.getPermission_name());
                map.put("fn", "modify");
                operaButton.add(map);
            }
//            if (bean.getPermission_url().equals("/user/detail.page")) {
//                Map map = new HashMap();
//                map.put("name", bean.getPermission_name());
//                map.put("fn", "detail");
//                operaButton.add(map);
//            }
        }
        if (StringUtils.isBlank(key)) {
            key = "''";
        }
        if (operaButton.size() == 0) {
            Map map = new HashMap();
            map.put("name", "--");
            operaButton.add(map);
        }
        Map resultMap = new HashMap();
        resultMap.put("list", list);
        resultMap.put("total", count == 0 ? 1 : count);
        resultMap.put("operaButton", operaButton);
        resultMap.put("key", key);
        resultMap.put("pageIndex", page);
        resultMap.put("size", size);
        return JsonData.success(resultMap);
    }

    /**
     * 用户离职
     *
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cancel.json", method = RequestMethod.POST)
    public JsonData roleListJson(int userId) throws Exception {
        Optional<UserBean> optional = userService.findById(userId);
        if (!optional.isPresent()) {
            return JsonData.fail("用户不存在");
        }
        UserBean bean = optional.get();
        if ("11".equals(bean.getUser_state())) {
            bean.setUser_state("99");
        } else {
            bean.setUser_state("11");
        }
        userService.save(bean);
        return JsonData.success();
    }

    /**
     * 添加用户界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add.page", method = RequestMethod.GET)
    public ModelAndView add() throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("userType", SpringSecurityUtils.getCurrentUser().getUser_type());
        mv.setViewName("/user/add");
        return mv;
    }


    /**
     * 用户注册
     *
     * @param userBean      用户对象
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "用户注册", notes = "用户注册")
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public JsonData registerUser(@Valid UserBean userBean, BindingResult bindingResult) {
        log.error("************");
        try {
            //验证提交数据是否合法
            if (bindingResult.hasErrors()) {
                return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
            }

            //1、验证本地用户是否存在。
            UserBean bean = new UserBean();
            bean.setUser_email(userBean.getUser_email());
            boolean bool = userService.isExisit(bean);
            //result>0该用户名存在，不可以注册，否则没有被注册，可以注册。
            if (bool) {
                return JsonData.fail("用户添加失败，该邮箱已被注册，请更改邮箱");
            }
            UserDetail userInfo = SpringSecurityUtils.getCurrentUser();
            userBean.setUser_password("{noop}" + StringUtil.EncoderByMd5(userBean.getUser_password()));
//            Map<String,String> map = new HashMap<>();
//            map.put("user_name",userBean.getUser_name());
//            map.put("user_password",userBean.getUser_password());
//            map.put("user_phone",userBean.getUser_phone());
//            map.put("user_email",userBean.getUser_email());
//           String resultmap = HttpUtil.httpPost(StaticUtil.changeCenter+"/insert.json",map);
            userBean.setCreat_time(new Date());
            userBean.setUser_state("11");
            boolean companyBool = StringUtils.isNotBlank(userBean.getCompany_id());
            if (companyBool) {
                userBean.setUser_type("88");
            } else {
                userBean.setCompany_id(userInfo.getCompany_id());
                userBean.setUser_type("11");
            }
            UserBean result = userService.save(userBean);

            GroupMemberBean groupMemberBean = new GroupMemberBean();
            groupMemberBean.setUser_id(String.valueOf(result.getId()));
            //企业id不为空，添加的是新企业用户
            if (companyBool) {
                if(userBean.getCompany_id().equals("20")){
                    //集栋管理员账号默认集栋权限列表
                    groupMemberBean.setGroup_id("107");
                }else{
                    //其他默认渠道商权限列表
                    groupMemberBean.setGroup_id("108");
                }
                groupMemberBean.setCompany_id(userBean.getCompany_id());
                groupMemberService.save(groupMemberBean);
            }
            //订阅表插入用户信息，默认不推送
            UserCenterBean userCenterBean = new UserCenterBean();
            userCenterBean.setUser_id(result.getId());
            userCenterBean.setUser_notify(false);
            userCenterService.save(userCenterBean);
            return JsonData.success();
        } catch (Exception e) {
            /**
             * 打印日志
             */
            return JsonData.fail();
        }

    }

    /**
     * 添加用户界面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/update.page", method = RequestMethod.GET)
    public ModelAndView update(String uid) throws Exception {
        ModelAndView mv = new ModelAndView();
        //得到用户详情
        Optional<UserBean> optional = userService.findById(Integer.valueOf(uid));
        UserBean bean = optional.get();
        //得到用户的角色组
        List<Integer> list = groupMemberService.findUserGroup(uid, bean.getCompany_id());

        mv.addObject("bean", bean);
        UserDetail detail = SpringSecurityUtils.getCurrentUser();
        if(detail.getId().equals(uid)){
            mv.addObject("boolean","false");
        }else{
            mv.addObject("boolean","true");

        }
        mv.addObject("groupId", StringUtil.ObjectToJson(list));
        mv.setViewName("/user/update");
        return mv;
    }


    @RequestMapping(value = "/update.json", method = RequestMethod.POST)
    public JsonData updateUser(@Valid UserBeanParam userBeanParam, BindingResult bindingResult) {
        try {
            //验证提交数据是否合法
            if (bindingResult.hasErrors()) {
                return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
            }
            //根据id获取用户详情
            Optional<UserBean> optional = userService.findById(userBeanParam.getId());
            UserBean bean = optional.get();
            bean.setUser_name(userBeanParam.getUser_name());
            bean.setUser_phone(userBeanParam.getUser_phone());
            bean.setUser_dept(userBeanParam.getUser_dept());
            //修改用户的基本信息
            userService.save(bean);
            //删除用户的角色组信息
            GroupMemberBean groupMemberBean = new GroupMemberBean();
            String companyId =bean.getCompany_id();
            groupMemberBean.setCompany_id(companyId);
            groupMemberBean.setUser_id(String.valueOf(bean.getId()));
            //查询用户所在的组列表
            List<GroupMemberBean> list = groupMemberService.findAll(groupMemberBean);
            for (GroupMemberBean result : list) {
                //删除用户绑定的组
                groupMemberService.delete(result);
            }
            //添加修改后的用户角色组
            String[] groupIds = userBeanParam.getGroup_id().split(",");
            for (int i = 0; i < groupIds.length; i++) {
                GroupMemberBean groupMemberBean1 = new GroupMemberBean();
                groupMemberBean1.setGroup_id(groupIds[i]);
                groupMemberBean1.setCompany_id(companyId);
                groupMemberBean1.setUser_id(String.valueOf(bean.getId()));
                groupMemberService.save(groupMemberBean1);
            }
            return JsonData.success();
        } catch (Exception e) {
            /**
             * 打印日志
             */
            return JsonData.fail(ErrMessageUtil.SysErr);
        }

    }


    /**
     * 修改用户信息
     *
     * @param userBean      用户对象
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "用户修改个人信息(普通用户修改个人基本信息，管理员修改用户组织信息。)", notes = "用户修改个人信息(普通用户修改个人基本信息，管理员修改用户组织信息。)")
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    public JsonData updateUser(@Valid UserBean userBean, BindingResult bindingResult) {
        //1、验证提交数据是否合法
        if (bindingResult.hasErrors()) {
            return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        //2、更新用户信息
//        int updateResult = userService.updateUserInfo(userBean);
//        //3、更新失败，返回异常信息
//        if (updateResult==0){
//            return JsonData.fail("用户信息更新失败，系统异常");
//        }
        return JsonData.success();
    }


    /**
     * 根据用户id查询用户详情
     *
     * @param userId 用户id
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据用户id查询用户", notes = "根据用户id查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户标识(若空则表示查询当前登陆用户信息，若不为空，则查传入用户信息。)", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/queryUser", method = RequestMethod.GET)
    public UserBean queryUserById(@RequestParam(value = "userId", required = false) String userId) throws Exception {
        Optional<UserBean> optional = userService.getUserDetail(userId);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @ApiOperation(value = "用户选择组页面", notes = "用户选择组页面")
    @RequestMapping(value = "/chooseGroupList.json", method = RequestMethod.POST)
    public JsonData chooseGroupList() {
        List<GroupBean> list = groupService.getUserGroupListByUserId();
        log.info("用户选择组json" + StringUtil.ObjectToJson(list));
        return JsonData.success(list);
    }

    @ApiOperation(value = "用户选择一个组并完成登陆", notes = "用户选择一个组并完成登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "groupId", value = "组id", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/chooseGroup.json", method = RequestMethod.POST)
    public JsonData chooseGroup(String groupId) {
//        ModelAndView mv = new ModelAndView();
        try {
            UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
            //根据groupId得到组详情
            Optional<GroupBean> optional = groupService.findById(Integer.valueOf(groupId));
            if (!optional.isPresent()) {
                return JsonData.fail("选择组不存在！");
            }
            UserBean userBean = userService.findUserDetail(String.valueOf(userDetail.getId()));
            GroupBean bean = optional.get();
            userDetail.setGroup_id(String.valueOf(groupId));
            userDetail.setCompany_type(userBean.getType());
            userDetail.setCompany_id(userBean.getCompany_id());
            List<PermissionBean> listBean = permissionService.findPermissionByGroupIdNotTree(String.valueOf(bean.getId()));//查看该组下是否有权限
//            if (listBean.size()>0){//有权限获取权限
            userDetail.setList(listBean);
//            }else {//无权限获取顶级组权限
//                listBean = permissionService.findPermissionByGroupIdNotTree(String.valueOf(bean.getTop_parent_id()));
//                userDetail.setList(listBean);
//            }
//            mv.addObject("result",listBean);
            return JsonData.success();
        } catch (Exception e) {
            /**
             * 打印日志
             */
            return JsonData.fail(ErrMessageUtil.SysErr);
        }
//        mv.setViewName("redirect:/index.page");

    }


    @RequestMapping("/getUserListByCompanyId.json")
    public JsonData findUserByCompanyId(String companyId) {
        List<UserBean> list = userService.findUserByCompanyId(companyId);
        return JsonData.success(list);
    }

    /**
     * 查询采购管理岗下人员
     * @return
     */
    @RequestMapping("/getUserListByGroupId.json")
    public JsonData findAllUserByGroupId(String groupId) {
        if(StringUtils.isNotBlank(groupId)){
            List<UserBean> list = userService.findAllUserByGroupId(groupId);
            return JsonData.success(list);
        }else{
            return JsonData.fail("角色组不可以为空");
        }

    }

}
